﻿using A2.ERP.DALFactory;
using A2.ERP.IDAL;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace A2.ERP.BLL
{
    public abstract class BaseService<T> where T : class,new()
    {
        public IDBSession DbSession
        {
            get
            {
                //return new DBSession();//如果直接new那么每执行一次就会new一次，为了提高性能需要保证它的唯一性
                return DBSessionFactory.CreateDbSession();
            }
        }

        //因为实现方法不知道要实现的是那张表的方法，所以需要继承的子类通过构造函数将实现基类传过来

        public IBaseDAL<T> CurrentDAL { get; set; }//对应的是所有接口的基类接口


        //实现之类传过来的类的方法
        public IQueryable<T> LoadEntities(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda)
        {
            return this.CurrentDAL.LoadEntities(whereLambda);
        }

        public IQueryable<T> LoadPageEntities<orderT>(int pageIndex, int pageSize, out int totalCount, Expression<Func<T, bool>> wherelamdba, Expression<Func<T, orderT>> orderby, bool isAsc)
        {
            return this.CurrentDAL.LoadPageEntities(pageIndex, pageSize, out totalCount, wherelamdba, orderby, isAsc);
        }

        public bool DeleEntity(T entity)
        {
            this.CurrentDAL.DeleEntity(entity);

            return this.DbSession.SaveChanges();
        }

        public bool UpdateEntity(T entity, params Expression<Func<T, object>>[] props)
        {
            this.CurrentDAL.UpdateEntity(entity, props);

            return this.DbSession.SaveChanges();
        }

        public T AddEntity(T entity)
        {
            this.CurrentDAL.AddEntity(entity);
            this.DbSession.SaveChanges();
            return entity;
        }

        //存储过程（测试）
        public List<T> Procedures<T>(string sql, params SqlParameter[] ps)
        {
            try
            {

            return this.CurrentDAL.Procedures<T>(sql, ps);
            }
            catch
            {
                return new List<T>();
            }
        }

    }
}
